package com.jeomo.masterdata.provider.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.jeomo.common.core.dto.ITree;
import com.jeomo.common.core.dto.PageQueryDto;
import com.jeomo.common.core.dto.PageResponseDto;
import com.jeomo.common.core.result.CommonResult;
import com.jeomo.common.core.util.BeanCopyUtil;
import com.jeomo.common.core.util.StringUtils;
import com.jeomo.common.core.util.TreeUtil;
import com.jeomo.masterdata.provider.request.ConfigWayRequest;
import com.jeomo.masterdata.provider.web.vo.*;
import com.jeomo.masterdata.starter.entity.Goods;
import com.jeomo.masterdata.starter.entity.GoodsType;
import com.jeomo.masterdata.starter.entity.Merchant;
import com.jeomo.masterdata.starter.entity.Tob;
import com.jeomo.masterdata.starter.enums.UseScopeEnum;
import com.jeomo.masterdata.starter.service.IGoodsService;
import com.jeomo.masterdata.starter.service.IGoodsTypeService;
import com.jeomo.masterdata.starter.service.IMerchantService;
import com.jeomo.masterdata.starter.service.ITobService;
import com.jeomo.shiro.util.LoginSessionUtil;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <h3>excel-util</h3>
 * <p>配置所需的controller</p>
 *
 * @author : 崔贺
 * @date : 2020-12-30 15:58
 * <p>
 * 业态、品类：
 * 左侧为业态和品类的树状图，右侧默认展示为树状图全部内容；
 * 点击左侧一级内容，右侧显示所有子集；
 * 点击左侧2级内容，右侧显示所有子集；
 * 商户、商品：
 * 左侧：商户的左侧内容为业态（树状），右侧默认展示全部商户；
 * 商品的左侧内容为商户，右侧默认展示全部商品；
 * 点击左侧业态/商户内容，右侧显示业态/商户分类下的商户/商品；
 */
@RequestMapping("/config")
@RestController
public class ConfigWayController {
    @Resource
    private IGoodsTypeService goodsTypeService;
    @Resource
    private IMerchantService merchantService;
    @Resource
    private ITobService tobService;
    @Resource
    private IGoodsService goodsService;

    @GetMapping("/way/{type}")
    public CommonResult<Object> getConfigWay(@PathVariable("type") String type) throws IllegalAccessException, NoSuchFieldException, InstantiationException {
        Map<String, Object> map = new HashMap<>(8);
        map.put("type", "tree");
        if (UseScopeEnum.MERCHANT.getCode().equals(type)) {
            List<T> tobList = handle(tobService, false);
            List<ITree> nodes = BeanCopyUtil.copyListProperties(tobList, TobTreeVo::new);
            map.put("data", TreeUtil.buildTree(nodes));
            return CommonResult.success(map);
            //商品的左侧内容为商户
        } else if (UseScopeEnum.GOODS.getCode().equals(type)) {
            QueryWrapper<Merchant> wrapper = new QueryWrapper<>();
            wrapper.eq("start_flag", true);
            wrapper.eq("org_code", LoginSessionUtil.getCurrentLoginInfo().getCurrentOrgCode());
            List<Merchant> merchants = merchantService.list(wrapper);
            map.put("data", BeanCopyUtil.copyListProperties(merchants, MerchantVo::new));
            return CommonResult.success(map);
        } else if (UseScopeEnum.GOODS_TYPE.getCode().equals(type)) {
            List<T> goodsTypes = handle(goodsTypeService, true);
            map.put("data", BeanCopyUtil.copyListProperties(goodsTypes, GoodsTypeVo::new));
            return CommonResult.success(map);
        } else if (UseScopeEnum.TOB.getCode().equals(type)) {
            List<T> tobList = handle(tobService, true);
            map.put("data", BeanCopyUtil.copyListProperties(tobList, TobVo::new));
            return CommonResult.success(map);
        }
        return CommonResult.failure("type无效");
    }

    @PostMapping("/selectTreeList")
    public CommonResult<Object> select(@RequestBody ConfigWayRequest configWayRequest) throws IllegalAccessException, NoSuchFieldException, InstantiationException {
        String code = configWayRequest.getCode();
        String type = configWayRequest.getType();
        if (UseScopeEnum.MERCHANT.getCode().equals(type)) {
            if (StringUtils.isNotEmpty(code)) {
                //左侧业态不做隔离，点击的获取商户的时候做隔离
                List<Merchant> merchants = merchantService.selectMerchantByTobCode(code, LoginSessionUtil.getCurrentLoginInfo().getCurrentOrgCode());
                return CommonResult.success(BeanCopyUtil.copyListProperties(merchants, MerchantVo::new));
            } else {
                return CommonResult.failure();
            }
        } else if (UseScopeEnum.GOODS.getCode().equals(type)) {
            PageQueryDto pageQueryDto = BeanCopyUtil.copyProperties(configWayRequest, PageQueryDto.class);
            //如果 不传code 获取所有商户下的所有商品
            if (StringUtils.isEmpty(code)) {
                QueryWrapper<Merchant> wrapper = new QueryWrapper<>();
                wrapper.eq("start_flag", true);
                wrapper.eq("org_code", LoginSessionUtil.getCurrentLoginInfo().getCurrentOrgCode());
                List<Merchant> merchants = merchantService.list(wrapper);
                //获取所有商户的code
                List<String> merchantCodes = new ArrayList<>();
                for (Merchant merchant : merchants) {
                    merchantCodes.add(merchant.getCode());
                }
                PageResponseDto<Goods> dto = goodsService.pageSearchByMerchantCodes(pageQueryDto, merchantCodes);
                return CommonResult.success(BeanCopyUtil.copyPageProperties(dto, GoodsVo.class));
            } else {
                List<String> merchantCodes = new ArrayList<>();
                merchantCodes.add(code);
                PageResponseDto<Goods> dto = goodsService.pageSearchByMerchantCodes(pageQueryDto, merchantCodes);
                return CommonResult.success(BeanCopyUtil.copyPageProperties(dto, GoodsVo.class));
            }
        } else if (UseScopeEnum.GOODS_TYPE.getCode().equals(type)) {
            QueryWrapper<GoodsType> wrapper = new QueryWrapper<>();
            wrapper.eq("start_flag", true);
            List<GoodsType> goodsTypeList = goodsTypeService.list(wrapper);
            List<ITree> nodes = BeanCopyUtil.copyListProperties(goodsTypeList, GoodsTypeTreeVo::new);
            List<ITree> iTrees = TreeUtil.buildTree(nodes, code, false);
            List<GoodsTypeTreeVo> goodsTypeTreeVos = new ArrayList<>();
            getGoodsTypeLeafNode(iTrees, goodsTypeTreeVos);
            return CommonResult.success(goodsTypeTreeVos);
        } else if (UseScopeEnum.TOB.getCode().equals(type)) {
            QueryWrapper<Tob> wrapper = new QueryWrapper<>();
            wrapper.eq("start_flag", true);
            List<Tob> tobList = tobService.list(wrapper);
            List<ITree> nodes = BeanCopyUtil.copyListProperties(tobList, TobTreeVo::new);
            List<ITree> iTrees = TreeUtil.buildTree(nodes, code, false);
            List<TobTreeVo> tobTreeVos = new ArrayList<>();
            getTobLeafNode(iTrees, tobTreeVos);

            return CommonResult.success(tobTreeVos);
        }
        return CommonResult.failure("type无效");

    }

    public List<String> getChildTreeByTobCode(List<Tob> tobList, String tobCode, List<String> tobCodeList) {
        if (!tobList.isEmpty()) {
            for (Tob tob : tobList) {
                if (tob.getParentCode().equals(tobCode)) {
                    getChildTreeByTobCode(tobList, tob.getCode(), tobCodeList);
                    tobCodeList.add(tob.getCode());
                }
            }
        }
        return tobCodeList;
    }

    /**
     * @param iTrees  树
     * @param tobList 叶子结点集合
     * @description: 获取叶子结点
     * @return: void
     * @author: 崔贺
     * @time: 2021/1/5 19:10
     */
    public void getTobLeafNode(List<ITree> iTrees, List<TobTreeVo> tobList) {
        for (ITree node : iTrees) {
            if (node instanceof TobTreeVo) {
                TobTreeVo tobTreeVo = (TobTreeVo) node;
                List<TobVo> children = tobTreeVo.getChildren();
                boolean add = children == null || children.isEmpty() && "1".equals(tobTreeVo.getNodeType());
                if (add) {
                    tobList.add(tobTreeVo);
                } else {
                    List<ITree> nodes = BeanCopyUtil.copyListProperties(children, TobTreeVo::new);
                    getTobLeafNode(nodes, tobList);
                }
            }
        }
    }

    /**
     * @param iTrees        树
     * @param goodsTypeList 叶子结点集合
     * @description: 获取叶子结点
     * @return: void
     * @author: 崔贺
     * @time: 2021/1/5 19:10
     */
    public void getGoodsTypeLeafNode(List<ITree> iTrees, List<GoodsTypeTreeVo> goodsTypeList) {
        for (ITree node : iTrees) {
            if (node instanceof GoodsTypeTreeVo) {
                GoodsTypeTreeVo goodsTypeTreeVo = (GoodsTypeTreeVo) node;
                List<GoodsTypeTreeVo> children = goodsTypeTreeVo.getChildren();
                boolean add = children == null || children.isEmpty() && "1".equals(goodsTypeTreeVo.getNodeType());
                if (add) {
                    goodsTypeList.add(goodsTypeTreeVo);
                } else {
                    List<ITree> nodes = BeanCopyUtil.copyListProperties(children, GoodsTypeTreeVo::new);
                    getGoodsTypeLeafNode(nodes, goodsTypeList);
                }
            }
        }
    }

    /**
     * @param service      注入的service
     * @param isParentList 因为业态和品类左侧只需要输出父节点，所以加这个标志来做判断
     * @description:
     * @return: java.util.List<org.apache.poi.ss.formula.functions.T>
     * @author: 崔贺
     * @time: 2021/1/6 16:55
     */
    public List<T> handle(IService service, Boolean isParentList) {
        QueryWrapper<T> wrapper = new QueryWrapper<>();
        wrapper.eq("start_flag", true);
        if (isParentList) {
            wrapper.eq("parent_code", "0");
        }
        return service.list(wrapper);
    }

}

